package com.vecspace.dayu.code.httphandler;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.vecspace.dayu.code.model.ProjectVO;
import com.vecspace.dayu.code.pojo.Project;
import com.vecspace.dayu.code.pojo.ProjectCatalog;
import com.vecspace.dayu.code.service.ProjectCatalogService;
import com.vecspace.dayu.code.service.ProjectService;
import com.vecspace.dicttable.CodeItem;
import com.vecspace.dicttable.DictAll;
import com.vecspace.jsmodel.ZTreeNode;
import com.vecspace.security.model.LoginContext;
import com.vecspace.utils.Convert;
import com.vecspace.utils.TJSON;
import com.vecspace.web.servlet.model.BaseController;
import com.vecspace.web.servlet.model.HController;
import com.vecspace.web.servlet.model.NullValue;
import com.vecspace.web.servlet.model.Param;
import com.vecspace.web.servlet.model.Path;

/** DAYU-项目定义 httphandler
 * 在handler中进行与页面相关的处理，比如把数据转换为HTML格式等。
 * @author wanghua
 * @reviewer
 * @template wanghua
*/
@HController("dayucode_projectHandler")
public class ProjectHandler extends BaseController {

	/**根据ID查询 DAYU-项目定义
	 * @return Project
	 * @throws Exception
	 * @author wanghua
	 */
	@Path("getProject")
	public Project getProject(@Param("id") Long id) throws Exception {		
		Project project = projectService.getProject(id);
		return project;
	}
	
	/**根据ID查询 DAYU-项目定义
	 * @return Project
	 * @throws Exception
	 * @author wanghua
	 */
	@Path("getProjectVO")
	public ProjectVO getProjectVO(@Param("id") Long id) throws Exception {		
		Project project = projectService.getProject(id);
		ProjectVO projectVO = new ProjectVO(project);

		List<CodeItem> dbTypes = DictAll.getItems(Project.DbTypeCode);
		projectVO.setDbTypes(dbTypes);
		
		return projectVO;
	}
	
	/**获取项目结构树
	 * @param pId
	 * @return
	 * @throws Exception 
	 * @author wanghua
	 */
	@Path("getProjectTreeNodes")
	public List<ZTreeNode> getProjectTreeNodes(@Param("pId")String pId) throws Exception{
		List<ZTreeNode> nodes = new ArrayList<>();
		if(StringUtils.isEmpty(pId) || "-1".equals(pId)) {
			List<ProjectCatalog> catalogs = projectCatalogService.getChildProjectCatalogs(-1L);
			for(ProjectCatalog catalog : catalogs) {
				ZTreeNode node = new ZTreeNode("cat-"+catalog.getId(),"-1", catalog.getName(), null, catalog.getOrdnum());
				node.setIsParent(true);
				nodes.add(node);
			}
		}else if(pId.startsWith("cat-")){
			Long catalogId = Convert.toLong(pId.substring(4), -1L);
			List<ProjectCatalog> catalogs = projectCatalogService.getChildProjectCatalogs(catalogId);

			for(ProjectCatalog catalog : catalogs) {
				ZTreeNode node = new ZTreeNode("cat-"+catalog.getId(),"-1", catalog.getName(), null, catalog.getOrdnum());
				node.setIsParent(true);
				nodes.add(node);
			}

			List<Project> projects = projectService.getProjects(catalogId);
			for(Project project : projects) {
				ZTreeNode node = new ZTreeNode("prj-"+project.getId(), "cat-"+ project.getCatalogId(), project.getName(), null, project.getOrdnum());
				nodes.add(node);
			}
		}
		return nodes;
	}

	@Path("getProjects")
	public List<Project> getProjects(@Param("catalogId") Long catalogId) throws Exception{
		List<Project> projects = projectService.getProjects(catalogId);
		return projects;
	}
	
	@Path("getAllProjects")
	public List<Project> getAllProjects() throws Exception{
		List<Project> projects = projectService.getAllProjects();
		return projects;
	}
	
	/** 插入或修改 DAYU-项目定义 
	 * @param item	要保存的对象
	 * @return void
	 * @throws Exception
	 * @author wanghua
	 */
	@Path("saveProject")
	public Project saveProject(@Param("item") Project item) throws Exception {
		if (item == null){
			return null;
		}
		/*** 对item对象进行校验，如必填项，格式，逻辑关系等 ***/
		String loginId = LoginContext.getLoginId();
		return projectService.saveViewProject(item, loginId);
	}

	/** 根据ID删除 DAYU-项目定义 
	 * @param id	主键值
	 * @return void
	 * @throws Exception
	 * @author wanghua
	 */
	@Path("deleteProject")
	public void deleteProject(@Param("id") Long id) throws Exception {
		projectService.deleteProject(id);
	}
	
	@Path("uploadPdmFile")
	public Object uploadPdmFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String,Object> fileInfo = new HashMap<String,Object>();
		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
		for (MultipartFile multipartFile : multipartRequest.getFileMap().values()) {
			
			CommonsMultipartFile cFile = (CommonsMultipartFile) multipartFile;
			String orgFileName = cFile.getOriginalFilename();
			if(orgFileName == null || orgFileName.length()==0)continue;
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String newFileName = uuid;
			String extName = "";
			int dotIndex = orgFileName.lastIndexOf('.');
			if(dotIndex >0){
				extName = orgFileName.substring(dotIndex);
				newFileName = uuid + extName;
			}

			String pdmFileDir = projectService.getPdmFileDir();
			File path = new File(pdmFileDir);
			if(!path.exists()){
				path.mkdirs();
			}
			
			//by wanghua 在大规模使用的情况下，需要分目录存储。
			String newFileFullName = pdmFileDir + File.separator + newFileName;
			File uploadedFile = new File(newFileFullName);
			cFile.transferTo(uploadedFile);

			fileInfo.put("orgFileName", orgFileName);
			fileInfo.put("newFileName", newFileName);
		}

		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		String resultString = TJSON.toJSONString(fileInfo);
		PrintWriter out = response.getWriter();
		out.println(resultString);
		out.flush();
		out.close();
		
		return NullValue.value;
	}
	
	@Path("downloadPdmFile")
	public Object downloadPdmFile(HttpServletRequest request, HttpServletResponse response,@Param("path")String path) throws IOException {
		String message = "";
		String fileFullName = projectService.getAbsPdmFilePath(path);
		File pdmFile = new File(fileFullName);
		if(!pdmFile.exists()) {
			response.sendError(404,"File not found!");
			return "File not found!";
		}else {
			BufferedInputStream br = new BufferedInputStream(new FileInputStream(pdmFile));
			try{
				byte[] buf = new byte[1024];
				int len = 0;
	
				response.reset(); //非常重要
				response.setContentType("application/x-msdownload"); 
				String orgFileName = path;
				response.setHeader("Content-Disposition", "attachment; filename=" + new String(orgFileName.getBytes("gb2312"), "ISO8859-1" )); 
				OutputStream out = response.getOutputStream();
				try{
					while((len = br.read(buf)) >0){
						out.write(buf,0,len);
					}
				}finally{
					out.close();
				}
			}finally{
				br.close();
			}
			message = "success";
		}
		return message;
	}
	

	/************* property ********************/
	
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private ProjectCatalogService projectCatalogService;

}
